import {useRouter} from "next/router";
import {useEffect} from "react";
import {login} from "@/service/api";
import Cookies from 'js-cookie';
import url from "url";
import querystring from "querystring";
import {COOKIE_KEY, LOGIN_KEY} from "@/utils";

// 定义一个类型来描述期望的查询参数
interface QueryParams {
    audioId?: string;
    wxUid?: string;
    inviteId?: string;
}

export default function LoginRedirect() {
    const router = useRouter();

    function setUserInfo(data: any) {
        console.log(JSON.stringify(data))
        localStorage.setItem(LOGIN_KEY, JSON.stringify(data))
        // localStorage.setItem('info_str', JSON.stringify(data))
        Cookies.set(COOKIE_KEY, JSON.stringify(data), {expires: 7, path: '/'});
    }

    function redirect() {
        const returnUrl = router.query.returnUrl;
        if (returnUrl) {
            window.location.href = returnUrl as string
        } else {
            window.location.href = '/my'
        }
    }

    useEffect(() => {
        if (router.isReady) {
            const wechat_code: any = router.query.code;
            const returnUrl = router.query.returnUrl;
            console.log('wechat_code---',wechat_code,'returnUrl-------',router.query)
            // 使用 url.parse 方法解析 URL
            const parsedUrl = url.parse(returnUrl as string);
            // 使用 querystring.parse 方法解析查询字符串
            const parsedQuery = querystring.parse(parsedUrl.query as string) as QueryParams;
            console.log('wechat code', wechat_code)
            if (wechat_code) {
                const params: API.LoginParams = {
                    code: wechat_code,
                    audioId: parsedQuery.audioId,
                    wxUid: parsedQuery.wxUid,
                    inviterUnionid: parsedQuery.inviteId,
                }
                login(params).then(res => {
                    console.log('login res', res)
                    if (res.code === 1) {
                        console.log('登录成功')
                        setUserInfo(res.data)
                        redirect()
                    } else {
                        alert('登录失败,' + res.msg)
                    }
                })
            } else {
                console.log('登录失败')
            }
        }
        console.log('end process wechat code')
    }, [router.isReady, router.query]); // 依赖项数组中包含router.query，以确保参数更新时重新执行

    return (
        <>
        </>
    )
}
